use bleps::att::Uuid;
use esp_hal::delay::Delay;
use esp_hal::peripheral::Peripheral;
use esp_hal::peripherals::{BT, RADIO_CLK, RNG, TIMG0};
use esp_hal::rng::Rng;
use esp_hal::time;
use esp_hal::timer::timg::TimerGroup;
use esp_println::println;
use esp_wifi::ble::controller::BleConnector;
use esp_wifi::EspWifiTimerSource;
use bleps::{
    ad_structure::{
        create_advertising_data,
        AdStructure,
        BR_EDR_NOT_SUPPORTED,
        LE_GENERAL_DISCOVERABLE,
    },
    attribute_server::{AttributeServer, NotificationData, WorkResult},
    gatt,
    Ble,
    HciConnector,
};
use embassy_time::Timer;
use slint::Weak;

pub struct BlePeripherals{
    pub timer0: TimerGroup<TIMG0>,
    pub rng:RNG,
    pub radio_clk: RADIO_CLK,
    pub bt: BT
}


#[embassy_executor::task]
pub async  fn start(
    timer0: TimerGroup<TIMG0>,
    rng:RNG,
    radio_clk: RADIO_CLK,
    mut bt: BT,
){
    let esp_wifi_controller = esp_wifi::init(timer0.timer0, Rng::new(rng), radio_clk).unwrap();

    let now = || time::Instant::now().duration_since_epoch().as_millis();
    loop {
        let connector = BleConnector::new(&esp_wifi_controller, &mut bt);
        let hci = HciConnector::new(connector, now);
        let mut ble =Ble::new(&hci);

        println!("{:?}", ble.init());
        println!("{:?}", ble.cmd_set_le_advertising_parameters());
        println!(
            "{:?}",
            ble.cmd_set_le_advertising_data(
                // 广播设置
                create_advertising_data(&[
                    //                 通用可发现模式              不支持传统蓝牙
                    AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED),
                    AdStructure::ServiceUuids16(&[Uuid::Uuid16(0x1809)]), // 扫描的服务uuid
                    AdStructure::CompleteLocalName(esp_hal::chip!()), // esp_hal::chip!()这个函数会获取当前芯片的名字
                ])
                    .unwrap()
            )
        );
        // 命名习惯，le 表示该函数与 蓝牙低功耗协议（BLE） 相关。
        println!("{:?}", ble.cmd_set_le_advertise_enable(true));

        println!("started advertising");

        // f表示function，读函数
        let mut rf = |_offset: usize, data: &mut [u8]| {
            data[..20].copy_from_slice(&b"Hello Bare-Metal BLE"[..]);
            17
        };
        let mut wf = |offset: usize, data: &[u8]| {
            println!("RECEIVED: {} {:?}", offset, data);
        };

        let mut wf2 = |offset: usize, data: &[u8]| {
            println!("RECEIVED: {} {:?}", offset, data);
        };

        let mut rf3 = |_offset: usize, data: &mut [u8]| {
            data[..5].copy_from_slice(&b"Hola!"[..]);
            5
        };
        let mut wf3 = |offset: usize, data: &[u8]| {
            println!("RECEIVED: Offset {}, data {:?}", offset, data);
        };

        // 创建一个名为 gatt_attributes 定义给定服务的数组
        gatt!([service {
            uuid: "ad91b201-7347-4047-9e17-3bed82d75f9d",
            characteristics: [
                /*characteristic {
                    uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38",
                    read: rf,
                    write: wf,
                },*/
                characteristic {
                    uuid: "b6fccb50-87be-44f3-ae22-f85485ea42c4",
                    write: wf2,
                },
/*                characteristic {
                    name: "my_characteristic",
                    uuid: "503de214-8682-46c4-828f-d59144da41be",
                    notify: true,
                    read: rf3,
                    write: wf3,
                },*/
            ],
        },]);


        let mut rng = bleps::no_rng::NoRng;
        let mut srv = AttributeServer::new(&mut ble, &mut gatt_attributes, &mut rng);

        let delay = Delay::new();
        let mut num:i32 = 0;
        loop{
            srv.do_work().unwrap();
            Timer::after_millis(100).await;
        }


    }
}